import { createRouter, createWebHashHistory } from 'vue-router'
import storage from '../utils/storage'
import utils from '../utils/utils'
import API from '../api'
const routes = [
  {
    name: 'home',
    path: '/',
    meta: {
      title: '首页',
    },
    component: () => import('@/components/Home.vue'),
    redirect: '/welcome',
    children: [
      {
        name: 'welcome',
        path: '/welcome',
        meta: {
          title: '欢迎体验Vue3全栈课程',
        },
        component: () => import('@/views/Welcome.vue'),
      },
    ],
  },
  {
    name: 'login',
    path: '/login',
    meta: {
      title: '登录页面',
    },
    component: () => import('@/views/Login.vue'),
  },
  {
    name: '404',
    path: '/404',
    meta: {
      title: '404页面',
    },
    component: () => import('@/views/404.vue'),
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

async function loadAsyncRoutes() {
  let userInfo = storage.getItem('userInfo') || {}
  if (userInfo.token) {
    try {
      const { menuList } = await API.getPermissionList()
      let routes = utils.generateRoute(menuList)
      routes.map((route) => {
        let url = `./../views/${route.component}.vue`
        route.component = () => import(/* @vite-ignore */url)
        router.addRoute('home', route)
      })
    } catch (error) {}
  }
}

loadAsyncRoutes()
const userInfo = storage.getItem('userInfo') || {}
const token = userInfo.token
// 导航守卫
router.beforeEach((to, from, next) => {
  if (router.hasRoute(to.name)) {
    document.title = to.meta.title
    next()
  } else {
    next('/404')
  }
})

export default router
